//
//  UIImage+SJBGColor.swift
//  Employee
//
//  Created by swordjoy on 2017/3/30.
//  Copyright © 2017年 remotevillage. All rights reserved.
//

import Foundation
import UIKit

public extension UIImage {
    // 适配屏幕
    // 宽设为屏幕宽
    // 按比例算出高
    public var previewSize: CGSize {
        let width = UIScreen.width
        let height = self.size.height * ( width / self.size.width )
        return CGSize(width: width, height: height)
    }
    
    // 直接根据previewSize强行绘制新的image
    // 一般不用,让UIImageView自己根据previewSize fill
   public var previewImage: UIImage? {
        let temp = self.resizeImage(to: self.previewSize)
        return temp
    }
    
   public func resizeImage(to newSize: CGSize) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(newSize, true, UIScreen.main.scale)
        self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage
    }
  public static func getImage(with color: UIColor, size: CGSize) -> UIImage {
    
    let rect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height)
    UIGraphicsBeginImageContext(rect.size)
    let context: CGContext? = UIGraphicsGetCurrentContext()
    context?.setFillColor(color.cgColor)
    context?.fill(rect)
    let image  = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    if let i = image {
        return i
    }
    return UIImage()
    
  }
  
  public static func cropImage(with image: UIImage, rect: CGRect) -> UIImage {
    let scale = UIScreen.main.scale
    let sacleRect = CGRect(x: (rect.origin.x + 1) * scale, y: (rect.origin.y + 1) * scale, width: (rect.width - 2) * scale, height: (rect.height - 2) * scale)
    let subImageRef: CGImage? = image.cgImage?.cropping(to: sacleRect)
    UIGraphicsBeginImageContext(rect.size)
    let context: CGContext? = UIGraphicsGetCurrentContext()
    context?.draw(subImageRef!, in: sacleRect)
    let image = UIImage(cgImage: subImageRef!)
    UIGraphicsEndImageContext()
    return image
  }
  
  func sampleHandle() -> Data {
    
    let imageData = UIImageJPEGRepresentation(self, 1.0)!
    let size = imageData.count / 1024
    
    // 大于500kb压缩
    if size > 500 {
      // 第一次0.5系数压缩
      let data5 = UIImageJPEGRepresentation(self, 0.3)!
      let size5 = imageData.count / 1024
      // 如果还大于 500kb
      if size5 > 500 {
        // 第二次0.3压缩后直接上传
        let data3 = UIImageJPEGRepresentation(self, 0.3)!
        return data3
      } else { return data5 }
    }
    else { return imageData }
  }
  
  func sampleHandleToImage() -> UIImage {
    
    return UIImage(data: self.sampleHandle()) ?? UIImage()
  
  }
  
  public func thumbnailCustom(to size: CGSize) -> UIImage {
    
    UIGraphicsBeginImageContext(size)
    
    self.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
    
    let image = UIGraphicsGetImageFromCurrentImageContext()
    
    UIGraphicsEndImageContext()
    
    return image!
    
  }
  
  public func thumbnailSquareOriginalScale(with width: CGFloat) -> UIImage {
    
    let oldSize = self.size
    
    var rect = CGRect.zero
    
    if oldSize.width > oldSize.height {
      
      rect.size.width = oldSize.width * width / oldSize.height
      rect.size.height = width
      rect.origin.x = 0
      rect.origin.y = 0
      
    }
    else {
      
      rect.size.width = width
      rect.size.height = oldSize.height * width / oldSize.width
      rect.origin.x = 0
      rect.origin.y = 0
      
    }
    
    UIGraphicsBeginImageContext(rect.size)
    let context = UIGraphicsGetCurrentContext()
    context!.setFillColor(UIColor.clear.cgColor)
    UIRectFill(rect)
    self.draw(in: rect)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    
    return image!
    
  }
  
  public static func drawLinearGradient(with context: CGContext, path: CGPath, startColor: CGColor, endColor: CGColor) {
    
    let colorSpace = CGColorSpaceCreateDeviceRGB()
    let locations: [CGFloat] = [0.0, 1.0]
    let colors: [Any]? = [(startColor as Any), (endColor as Any)]
    let gradient = CGGradient(colorsSpace: colorSpace, colors: (colors as CFArray?)!, locations: locations)
    let pathRect = path.boundingBox
    //具体方向可根据需求修改
    let startPoint = CGPoint(x: CGFloat(pathRect.minX), y: CGFloat(pathRect.midY))
    let endPoint = CGPoint(x: CGFloat(pathRect.maxX), y: CGFloat(pathRect.midY))
    context.saveGState()
    context.addPath(path)
    context.clip()
    context.drawLinearGradient(gradient!, start: startPoint, end: endPoint, options: [])
    context.restoreGState()
  }
  
  public static func getLinerGradientImage(with startColor: UIColor, endColor: UIColor, size: CGSize) -> UIImage {
    
    UIGraphicsBeginImageContext(size)
    let gc = UIGraphicsGetCurrentContext()
    //创建CGMutablePathRef
    let path = CGMutablePath()
    //绘制Path
    let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
    path.addRect(rect)
    path.closeSubpath()
    //绘制渐变
    drawLinearGradient(with: gc!, path: path, startColor: startColor.cgColor, endColor: endColor.cgColor)
    //注意释放CGMutablePathRef
    
    //从Context中获取图像，并显示在界面上
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    
    return image!
  }
    
    var uploadData: Data {
        let data = UIImageJPEGRepresentation(uploadImage, 0.5)!
        return data
    }
    
    /*
     据说仿照微信
     宽高均 <= 1280，图片尺寸大小保持不变
     宽或高 > 1280 && 宽高比 <= 2，取较大值等于1280，较小值等比例压缩
     宽或高 > 1280 && 宽高比 > 2 && 宽或高 < 1280，图片尺寸大小保持不变
     宽高均 > 1280 && 宽高比 > 2，取较小值等于1280，较大值等比例压缩
     */
    var uploadSize: CGSize {
        var width = self.size.width
        var height = self.size.height
        
        let boundary: CGFloat = 1280
        
        // 宽高均 <= 1280，图片尺寸大小保持不变
        guard width > boundary || height > boundary else {
            return CGSize(width: width, height: height)
        }
        
        let s = max(width, height) / min(width, height)
        // 宽高比 <= 2
        if s <= 2 {
            // 取较大值等于1280，较小值等比例压缩
            let x = max(width, height) / boundary
            if width > height {
                width = boundary
                height = height / x
            } else {
                height = boundary
                width = width / x
            }
        }
            // 宽高比 > 2
        else {
            // 取较小值等于1280，较大值等比例压缩
            if min(width, height) >= boundary {
                // 取较小值等于1280，较大值等比例压缩
                let x = min(width, height) / boundary
                if width < height {
                    width = boundary
                    height = height / x
                } else {
                    height = boundary
                    width = width / x
                }
            }
        }
        return CGSize(width: width, height: height)
    }
    
    // 这里变相调整了图片的方向
    var uploadImage: UIImage {
        UIGraphicsBeginImageContextWithOptions(uploadSize, false, self.scale)
        let rect = CGRect(x: 0, y: 0, width: uploadSize.width, height: uploadSize.height)
        self.draw(in: rect)
        let upImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return upImage!
    }
  
}
